import {
  Button,
  Col,
  InputNumber,
  Drawer,
  Form,
  Input,
  Row,
  Select,
  Switch,
  message,
  Card,
} from 'antd';
import React, { useEffect } from 'react';
import { useRequest } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { DeployService } from '../../service';
import { CreateReq, Deploy } from '../../vms';

const protocolOption = [
  {
    label: 'TCP',
    value: 'TCP',
  },
  {
    label: 'UDP',
    value: 'UDP',
  },
  {
    label: 'SCTP',
    value: 'SCTP',
  },
];

const DeployDetail: React.FC<{
  isCreate: boolean
  open: boolean
  record?: Deploy
  namespaces:
  | {
    label: string;
    value: string;
  }[]
  | undefined;
  onClose: () => void;
  onSuccess: () => void;
}> = ({ open, namespaces, isCreate, record, onClose, onSuccess }) => {

  const [form] = Form.useForm();

  const save = useRequest(isCreate ? DeployService.create : DeployService.update, {
    manual: true,
    onSuccess: (data) => {
      console.log(data);
      // @ts-ignore
      if (data?.deployment?.is_ok && data?.service?.is_ok) {
        message.success('deploy, svc保存成功');
        // @ts-ignore
      } else if (data?.deployment?.is_ok && !data?.service?.is_ok && data.is_create_svc) {
        message.success('deploy创建成功 svc保存失败');
        // @ts-ignore
      } else if (data?.deployment?.is_ok && !data?.service?.is_ok && !data.is_create_svc) {
        message.success('deploy保存成功');
      }
      if (onSuccess) {
        onSuccess();
      }
      form.resetFields();
      onClose();
    },
  });

  const closeHandle = () => {
    onClose()
    if (!isCreate) {
      form.resetFields()
    }
  }
  /**
   * volumes: --数据卷定义
  - name: config  --数据的名称，该名称要与volumeMounts中的name值保持一致
    configMap: --数据来源与configMap
      name: wel-config  --configMap的名称与上述创建的configMap中的name保持一致
      items:  --元素
      - key: config.properties  --对应configMap中data下面的key值
        path: config.properties  --把key对应的值放入到path对应的文件中，进入pod中查看其实是链接
   */

  const get_name = (name: string): string => {
    if (name.endsWith('-conf')) {
      return name
    }
    return `${name}-conf`
  }

  const onFinish = (values: CreateReq) => {
    console.log('Received values of form:', values);
    const volumes = values.volumes
    let data = values

    const containers = values.containers
    if (containers) {
      data.containers.forEach(e => {
        if (typeof e.command === 'string' && e.command) {
          e['command'] = e.command.toString().split(" ")
        }
        if (values) {
          e['volumeMounts'] = volumes?.map(item => ({ mountPath: `/etc/config/${item.name}`, name: get_name(item.name) }))
        }
      })
    }
    console.log('data of form:', data);
    save.run(data);
  };


  useEffect(() => {
    if (open && !isCreate) {
      form.setFieldsValue({
        replicas: record?.deployment.spec.replicas,
        namespace: record?.namespace,
        name: record?.deploy_name,
        containers: record?.deployment.spec.template.spec.containers.map(item => ({
          name: item.name,
          image: item.image,
          command: item.command?.join(' '),
          ports: item.ports.map(ii => ({
            name: ii.name,
            protocol: ii.protocol,
            containerPort: ii.containerPort,
          })),
        })),
        volumes: record?.deployment.spec.template.spec.volumes
      })
    }
  }, [isCreate, open, record])

  return (
    <>
      <Drawer
        title={isCreate ? "创建部署" : "更新部署"}
        width={720}
        onClose={closeHandle}
        open={open}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Form
          layout="vertical"
          hideRequiredMark
          form={form}
          onFinish={onFinish}
          initialValues={{
            replicas: 1,
            namespace: 'default',
            is_create_svc: false,
          }}
        >
          <Row gutter={24}>
            <Col span={10}>
              <Form.Item
                name="name"
                label="部署名称"
                rules={[{ required: true, message: '部署名称不能为空' }]}
              >
                <Input disabled={!isCreate} placeholder="DeployName" />
              </Form.Item>
            </Col>
            <Col span={9}>
              <Form.Item
                name="namespace"
                label="名称空间"
                rules={[{ required: true, message: '名称空间不能为空' }]}
              >
                <Select
                  disabled={!isCreate}
                  placeholder="namespace"
                  options={namespaces}
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="replicas"
                label="副本集"
                rules={[{ required: true, message: '副本集不能为空' }]}
              >
                <InputNumber max={20} min={1} style={{ width: 115 }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Card style={{ width: '100%', marginBottom: 15 }}>
              <Form.List
                initialValue={[{}]}
                name="containers"
                rules={[
                  {
                    validator: async (_, containers) => {
                      if (!containers || containers.length < 1) {
                        return Promise.reject(new Error('至少配置一个镜像'));
                      }
                    },
                  },
                ]}
              >
                {(fields, { add, remove }, { errors }) => (
                  <>
                    {fields.map((field) => (
                      <Card
                        key={field.name}
                        style={{ width: '100%', marginBottom: 15 }}
                        title="配置镜像"
                        extra={
                          <Button
                            disabled={!isCreate}
                            type="link"
                            onClick={() => remove(field.name)}
                          >
                            delete
                          </Button>
                        }
                      >
                        <Row gutter={24}>
                          <Col span={8}>
                            <Form.Item
                              {...field}
                              label="名称"
                              name={[field.name, 'name']}
                              rules={[
                                { required: true, message: '名称不能为空' },
                              ]}
                            >
                              <Input disabled={!isCreate} placeholder="name" />
                            </Form.Item>
                          </Col>
                          <Col span={16}>
                            <Form.Item
                              {...field}
                              label="镜像"
                              name={[field.name, 'image']}
                              rules={[
                                { required: true, message: '镜像不能为空' },
                              ]}
                            >
                              <Input placeholder="image" />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={24}>
                          <Col span={24}>
                            <Form.Item
                              {...field}
                              label="启动命令"
                              name={[field.name, 'command']}
                            >
                              <Input disabled={!isCreate} placeholder="command" />
                            </Form.Item>
                          </Col>

                        </Row>
                        <Form.List
                          name={[field.name, 'ports']}
                          initialValue={[{}]}
                          rules={[
                            {
                              validator: async (_, containers) => {
                                if (!containers || containers.length < 1) {
                                  return Promise.reject(
                                    new Error('至少配置一个端口映射'),
                                  );
                                }
                              },
                            },
                          ]}
                        >
                          {(portsFields, { add, remove }, { errors }) => (
                            <>
                              {portsFields.map((portsField) => (
                                <Card
                                  key={portsField.name}
                                  style={{ width: '100%', marginBottom: 15 }}
                                  title="配置端口"
                                  extra={
                                    <Button
                                      disabled={!isCreate}
                                      type="link"
                                      onClick={() => remove(portsField.name)}
                                    >
                                      delete
                                    </Button>
                                  }
                                >
                                  <Row gutter={24}>
                                    <Col span={8}>
                                      <Form.Item
                                        {...portsField}
                                        label="名称"
                                        name={[portsField.name, 'name']}
                                        rules={[
                                          {
                                            required: true,
                                            message: '名称不能为空',
                                          },
                                        ]}
                                      >
                                        <Input disabled={!isCreate} placeholder="name" />
                                      </Form.Item>
                                    </Col>

                                    <Col span={8}>
                                      <Form.Item
                                        initialValue={80}
                                        {...portsField}
                                        label="containerPort"
                                        name={[
                                          portsField.name,
                                          'containerPort',
                                        ]}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'containerPort不能为空',
                                          },
                                        ]}
                                      >
                                        <InputNumber
                                          style={{ width: 115 }}
                                          min={1}
                                          disabled={!isCreate}
                                          placeholder="containerPort"
                                        />
                                      </Form.Item>
                                    </Col>
                                    <Col span={8}>
                                      <Form.Item
                                        {...portsField}
                                        label="port"
                                        initialValue={'TCP'}
                                        name={[portsField.name, 'protocol']}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'protocol不能为空',
                                          },
                                        ]}
                                      >
                                        <Select
                                          disabled={!isCreate}
                                          placeholder="protocol"
                                          options={protocolOption}
                                          allowClear
                                        />
                                      </Form.Item>
                                    </Col>
                                  </Row>
                                </Card>
                              ))}
                              <Form.Item style={{ width: '100%' }}>
                                <Button
                                  disabled={!isCreate}
                                  style={{ width: '100%' }}
                                  type="dashed"
                                  onClick={() => add()}
                                  icon={<PlusOutlined />}
                                >
                                  添加端口配置
                                </Button>
                              </Form.Item>
                              <Form.ErrorList errors={errors} />
                            </>
                          )}
                        </Form.List>
                      </Card>
                    ))}
                    <Form.Item style={{ width: '100%' }}>
                      <Button
                        disabled={!isCreate}
                        style={{ width: '100%' }}
                        type="dashed"
                        onClick={() => add()}
                        icon={<PlusOutlined />}
                      >
                        添加镜像
                      </Button>
                    </Form.Item>
                    <Form.ErrorList errors={errors} />
                  </>
                )}
              </Form.List>
            </Card>
          </Row>

          <Row gutter={16}>
            <Card style={{ width: '100%', marginBottom: 15 }}>
              <Form.List
                name="volumes"
              >
                {(fields, { add, remove }, { errors }) => (
                  <>
                    {fields.map((field) => (
                      <Card
                        key={field.name}
                        style={{ width: '100%', marginBottom: 15 }}
                        title="配置文件"
                        extra={
                          <Button
                            disabled={!isCreate}
                            type="link"
                            onClick={() => remove(field.name)}
                          >
                            delete
                          </Button>
                        }
                      >
                        <Row gutter={24}>
                          <Col span={12}>
                            <Form.Item
                              {...field}
                              label="名称"
                              name={[field.name, 'name']}
                              rules={[
                                { required: true, message: '名称不能为空' },
                              ]}
                            >
                              <Input disabled={!isCreate} placeholder="name" />
                            </Form.Item>
                          </Col>
                          <Col span={12}>
                            <Form.Item
                              {...field}
                              label="配置集名称"
                              name={[field.name, 'configMap', 'name']}
                              rules={[
                                { required: true, message: '配置集名称不能为空' },
                              ]}
                            >
                              <Input placeholder="filename" />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Form.List
                          initialValue={[{}]}
                          name={[field.name, 'configMap', 'items']}
                          rules={[
                            {
                              validator: async (_, containers) => {
                                if (!containers || containers.length < 1) {
                                  return Promise.reject(
                                    new Error('至少配置一个路径映射'),
                                  );
                                }
                              },
                            },
                          ]}
                        >
                          {(portsFields, { add, remove }, { errors }) => (
                            <>
                              {portsFields.map((portsField) => (
                                <Card
                                  key={portsField.name}
                                  style={{ width: '100%', marginBottom: 15 }}
                                  title="配置路径"
                                  extra={
                                    <Button
                                      disabled={!isCreate}
                                      type="link"
                                      onClick={() => remove(portsField.name)}
                                    >
                                      delete
                                    </Button>
                                  }
                                >
                                  <Row gutter={24}>
                                    <Col span={12}>
                                      <Form.Item
                                        {...portsField}
                                        label="key"
                                        name={[portsField.name, 'key']}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'key不能为空',
                                          },
                                        ]}
                                      >
                                        <Input disabled={!isCreate} placeholder="key" />
                                      </Form.Item>
                                    </Col>

                                    <Col span={12}>
                                      <Form.Item
                                        {...portsField}
                                        label="path"
                                        name={[
                                          portsField.name,
                                          'path',
                                        ]}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'path不能为空',
                                          },
                                        ]}
                                      >
                                        <Input disabled={!isCreate} placeholder="path" />
                                      </Form.Item>
                                    </Col>

                                  </Row>
                                </Card>
                              ))}
                              <Form.Item style={{ width: '100%' }}>
                                <Button
                                  disabled={!isCreate}
                                  style={{ width: '100%' }}
                                  type="dashed"
                                  onClick={() => add()}
                                  icon={<PlusOutlined />}
                                >
                                  添加路径映射
                                </Button>
                              </Form.Item>
                              <Form.ErrorList errors={errors} />
                            </>
                          )}
                        </Form.List>
                      </Card>
                    ))}
                    <Form.Item style={{ width: '100%' }}>
                      <Button
                        disabled={!isCreate}
                        style={{ width: '100%' }}
                        type="dashed"
                        onClick={() => add()}
                        icon={<PlusOutlined />}
                      >
                        添加配置文件
                      </Button>
                    </Form.Item>
                    <Form.ErrorList errors={errors} />
                  </>
                )}
              </Form.List>
            </Card>
          </Row>

          {isCreate && (
            <>
              <Row gutter={12}>
                <Col span={6}>
                  <Form.Item
                    name="is_create_svc"
                    label="是否创建Service"
                    rules={[{ required: true, message: '是否创建Service不能为空' }]}
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.is_create_svc !== currentValues.is_create_svc
                    }
                  >
                    {({ getFieldValue }) =>
                      getFieldValue('is_create_svc') ? (
                        <Form.Item
                          name={['service', 'type']}
                          initialValue={'NodePort'}
                          label="type"
                          rules={[{ required: true, message: 'type不能为空' }]}
                        >
                          <Select
                            placeholder="type"
                            options={[
                              {
                                label: 'NodePort',
                                value: 'NodePort',
                              },
                              {
                                label: 'ClusterIP',
                                value: 'ClusterIP',
                              },
                            ]}
                            allowClear
                          />
                        </Form.Item>
                      ) : null
                    }
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                    prevValues.is_create_svc !== currentValues.is_create_svc
                  }
                >
                  {({ getFieldValue }) =>
                    getFieldValue('is_create_svc') ? (
                      <Card style={{ width: '100%', marginBottom: 15 }}>
                        <Form.List
                          name={['service', 'ports']}
                          rules={[
                            {
                              validator: async (_, containers) => {
                                if (!containers || containers.length < 1) {
                                  return Promise.reject(
                                    new Error('至少配置一个端口映射'),
                                  );
                                }
                              },
                            },
                          ]}
                        >
                          {(fields, { add, remove }, { errors }) => (
                            <>
                              {fields.map((field) => (
                                <Card
                                  key={field.name}
                                  style={{ width: '100%', marginBottom: 15 }}
                                  title="配置端口"
                                  extra={
                                    <Button
                                      type="link"
                                      onClick={() => remove(field.name)}
                                    >
                                      delete
                                    </Button>
                                  }
                                >
                                  <Row gutter={24}>
                                    <Col span={6}>
                                      <Form.Item
                                        {...field}
                                        label="名称"
                                        name={[field.name, 'name']}
                                        rules={[
                                          {
                                            required: true,
                                            message: '名称不能为空',
                                          },
                                        ]}
                                      >
                                        <Input placeholder="name" />
                                      </Form.Item>
                                    </Col>
                                    <Col span={6}>
                                      <Form.Item
                                        {...field}
                                        label="port"
                                        initialValue={80}
                                        name={[field.name, 'port']}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'port不能为空',
                                          },
                                        ]}
                                      >
                                        <InputNumber
                                          style={{ width: 115 }}
                                          min={1}
                                          placeholder="port"
                                        />
                                      </Form.Item>
                                    </Col>
                                    <Col span={6}>
                                      <Form.Item
                                        {...field}
                                        initialValue={80}
                                        label="targetPort"
                                        name={[field.name, 'targetPort']}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'targetPort不能为空',
                                          },
                                        ]}
                                      >
                                        <InputNumber
                                          min={1}
                                          style={{ width: 115 }}
                                          placeholder="targetPort"
                                        />
                                      </Form.Item>
                                    </Col>
                                    <Col span={6}>
                                      <Form.Item
                                        {...field}
                                        initialValue={'TCP'}
                                        label="protocol"
                                        name={[field.name, 'protocol']}
                                        rules={[
                                          {
                                            required: true,
                                            message: 'protocol不能为空',
                                          },
                                        ]}
                                      >
                                        <Select
                                          placeholder="protocol"
                                          options={protocolOption}
                                          allowClear
                                        />
                                      </Form.Item>
                                    </Col>
                                  </Row>
                                </Card>
                              ))}
                              <Form.Item style={{ width: '100%' }}>
                                <Button
                                  style={{ width: '100%' }}
                                  type="dashed"
                                  onClick={() => add()}
                                  icon={<PlusOutlined />}
                                >
                                  添加端口配置
                                </Button>
                              </Form.Item>
                              <Form.ErrorList errors={errors} />
                            </>
                          )}
                        </Form.List>
                      </Card>
                    ) : null
                  }
                </Form.Item>
              </Row>
            </>
          )}
          <Form.Item>
            <Button loading={save.loading} type="primary" htmlType="submit">
              {isCreate ? "创建" : '更新'}
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default DeployDetail;
